﻿@*
    For more information on enabling MVC for empty projects, visit https://go.microsoft.com/fwlink/?LinkID=397860
*@
@{
    Layout = null;
}
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>患者费用明细</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            color: #333;
        }

        .container {
            max-width: 1000px;
            margin: 0 auto;
            background: #fff;
            padding: 20px;
            box-shadow: 0 0 10px rgba(0,0,0,0.1);
        }

        .section {
            margin-bottom: 30px;
        }

        .section-title {
            font-size: 18px;
            font-weight: bold;
            border-bottom: 1px solid #eee;
            padding-bottom: 10px;
            margin-bottom: 15px;
        }

        .info-grid {
            display: grid;
            grid-template-columns: repeat(4, 1fr);
            gap: 15px;
        }

        .info-item {
            margin-bottom: 10px;
        }

        .info-label {
            font-weight: bold;
            margin-right: 5px;
        }

        table {
            width: 100%;
            border-collapse: collapse;
            margin-bottom: 20px;
        }

        th, td {
            border: 1px solid #ddd;
            padding: 8px;
            text-align: left;
        }

        th {
            background-color: #f2f2f2;
        }

        .order-summary {
            display: flex;
            justify-content: space-between;
            margin-bottom: 20px;
        }

        .order-summary-item {
            flex: 1;
        }

        .buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        button {
            padding: 8px 15px;
            cursor: pointer;
        }

        .save-btn {
            background-color: #4CAF50;
            color: white;
            border: none;
        }

        .cancel-btn {
            background-color: #f44336;
            color: white;
            border: none;
        }

        textarea {
            width: 100%;
            padding: 10px;
            margin-bottom: 20px;
            border: 1px solid #ddd;
            resize: vertical;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>患者费用明细</h1>

        <!-- Patient Information Section -->
        <div class="section">
            <div class="section-title">患者信息</div>
            <div class="info-grid" id="patient-info">
                <!-- Filled by JavaScript -->
            </div>
        </div>

        <!-- Visit Information Section -->
        <div class="section">
            <div class="section-title">就诊信息</div>
            <div class="info-grid" id="visit-info">
                <!-- Filled by JavaScript -->
            </div>
        </div>


        <!-- Order Information Section -->
        <div class="section">
            <div class="section-title">订单信息</div>
            <div class="order-summary">
                <div class="order-summary-item">
                    <div><span class="info-label">订单总额：</span><span id="order-total">0.00</span>（元）</div>
                    <div><span class="info-label">支付方式：</span><span id="payment-method">-</span></div>
                </div>
                <div class="order-summary-item">
                    <div><span class="info-label">卡内余额：</span><span id="card-balance">0.00</span>（元）</div>
                    <div><span class="info-label">订单状态：</span><span id="order-status">-</span></div>
                </div>
            </div>
            <div>
                <div><span class="info-label">订单编号：</span><span id="order-id">-</span></div>
                <div><span class="info-label">取消时间：</span><span id="cancel-time">-</span></div>
                <div><span class="info-label">下单时间：</span><span id="order-time">-</span></div>
                <div><span class="info-label">优惠金额：</span><span id="discount-amount">0.00</span>（元）</div>
            </div>
            <div>
                <label for="order-notes">订单备注：</label>
                <textarea id="order-notes" placeholder="请输入内容"></textarea>
            </div>
            <div class="buttons">
                <button class="save-btn" id="save-btn">保存</button>
                <button class="cancel-btn" id="cancel-btn">取消</button>
            </div>
        </div>
    </div>

    <script>

        // app.js - MVC Implementation

        // Model
        class PatientBillingModel {
            constructor() {
                this.patientData = null;
                this.visitData = null;
                this.feeItems = [];
                this.orderData = null;
            }

            async fetchData(orderId) {
                try {
                    // In a real app, these would be actual API calls
                    const responses = await Promise.all([
                        this.mockApiCall('/api/patient', { orderId }),
                        this.mockApiCall('/api/visit', { orderId }),
                        this.mockApiCall('/api/fees', { orderId }),
                        this.mockApiCall('/api/order', { orderId })
                    ]);

                    this.patientData = responses[0];
                    this.visitData = responses[1];
                    this.feeItems = responses[2];
                    this.orderData = responses[3];

                    return true;
                } catch (error) {
                    console.error('Error fetching data:', error);
                    return false;
                }
            }

            // Mock API call for demonstration
            mockApiCall(endpoint, data) {
                return new Promise((resolve) => {
                    setTimeout(() => {
                        // Mock data based on the endpoint
                        if (endpoint === '/api/patient') {
                            resolve({
                                name: '静脉窦',
                                cardNumber: 'B0006090000',
                                idType: '身份证号',
                                idNumber: '371850195507070909',
                                wechat: '七尾Sam',
                                phone: '18678900998',
                                address: '北京市朝阳区"静一静"小区'
                            });
                        } else if (endpoint === '/api/visit') {
                            resolve({
                                hospital: '北京市第一人民医院/东院',
                                doctorAddress: '北京市大兴区"静一静"8090号',
                                doctor: '赵马',
                                doctorTitle: '主任医师',
                                feeType: '西药费'
                            });
                        } else if (endpoint === '/api/fees') {
                            resolve([
                                { id: 1, name: '曹罗希考片', price: 60.00, quantity: 2, subtotal: 120.00 },
                                { id: 2, name: '阿司匹林格洛片', price: 40.00, quantity: 2, subtotal: 80.00 },
                                { id: 3, name: '曹罗希考片', price: 60.00, quantity: 2, subtotal: 120.00 },
                                { id: 4, name: '阿司匹林格洛片', price: 40.00, quantity: 2, subtotal: 80.00 }
                            ]);
                        } else if (endpoint === '/api/order') {
                            resolve({
                                total: 600.00,
                                paymentMethod: '就诊卡余额',
                                cardBalance: 2000.00,
                                status: '已支付',
                                orderId: 'JF2020081900008',
                                cancelTime: '2020-12-12 10:06:09',
                                notes: '',
                                orderTime: '2020-08-19 14:30:00',
                                discountAmount: 50.00
                            });
                        }
                    }, 300);
                });
            }

            saveNotes(notes) {
                // In a real app, this would send the notes to the server
                return new Promise((resolve) => {
                    setTimeout(() => {
                        this.orderData.notes = notes;
                        resolve(true);
                    }, 300);
                });
            }
        }

        // View
        class PatientBillingView {
            constructor() {
                this.patientInfoContainer = document.getElementById('patient-info');
                this.visitInfoContainer = document.getElementById('visit-info');
                this.feeDetailsTable = document.querySelector('#fee-details tbody');
                this.orderTotal = document.getElementById('order-total');
                this.paymentMethod = document.getElementById('payment-method');
                this.cardBalance = document.getElementById('card-balance');
                this.orderStatus = document.getElementById('order-status');
                this.orderId = document.getElementById('order-id');
                this.cancelTime = document.getElementById('cancel-time');
                this.orderTime = document.getElementById('order-time');
                this.discountAmount = document.getElementById('discount-amount');
                this.orderNotes = document.getElementById('order-notes');
                this.saveBtn = document.getElementById('save-btn');
                this.cancelBtn = document.getElementById('cancel-btn');
            }

            renderPatientInfo(data) {
                this.patientInfoContainer.innerHTML = `
                    <div class="info-item">
                        <span class="info-label">重症姓名：</span>
                        <span>${data.name}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">就诊卡号：</span>
                        <span>${data.cardNumber}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">证件类型：</span>
                        <span>${data.idType}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">证件号码：</span>
                        <span>${data.idNumber}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">微信服务：</span>
                        <span>${data.wechat}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">手机号码：</span>
                        <span>${data.phone}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">联系人地址：</span>
                        <span>${data.address}</span>
                    </div>
                `;
            }

            renderVisitInfo(data) {
                this.visitInfoContainer.innerHTML = `
                    <div class="info-item">
                        <span class="info-label">就诊医院：</span>
                        <span>${data.hospital}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">医师地址：</span>
                        <span>${data.doctorAddress}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">就诊医生：</span>
                        <span>${data.doctor}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">医生简称：</span>
                        <span>${data.doctorTitle}</span>
                    </div>
                    <div class="info-item">
                        <span class="info-label">费用类型：</span>
                        <span>${data.feeType}</span>
                    </div>
                `;
            }

            renderFeeDetails(items) {
                this.feeDetailsTable.innerHTML = items.map(item => `
                    <tr>
                        <td>${item.id}</td>
                        <td>${item.name}</td>
                        <td>${item.price.toFixed(2)}</td>
                        <td>${item.quantity}</td>
                        <td>${item.subtotal.toFixed(2)}</td>
                    </tr>
                `).join('');
            }

            renderOrderInfo(data) {
                this.orderTotal.textContent = data.total.toFixed(2);
                this.paymentMethod.textContent = data.paymentMethod;
                this.cardBalance.textContent = data.cardBalance.toFixed(2);
                this.orderStatus.textContent = data.status;
                this.orderId.textContent = data.orderId;
                this.cancelTime.textContent = data.cancelTime || '-';
                this.orderTime.textContent = data.orderTime || '-';
                this.discountAmount.textContent = data.discountAmount.toFixed(2);
                this.orderNotes.value = data.notes || '';
            }

            bindSaveNotes(handler) {
                this.saveBtn.addEventListener('click', () => {
                    const notes = this.orderNotes.value;
                    handler(notes);
                });
            }

            bindCancel(handler) {
                this.cancelBtn.addEventListener('click', handler);
            }

            showMessage(message, isError = false) {
                alert(message); // In a real app, you'd use a nicer notification system
            }
        }

        // Controller
        class PatientBillingController {
            constructor(model, view) {
                this.model = model;
                this.view = view;

                // Extract order ID from URL or use a default
                this.orderId = this.getOrderIdFromUrl() || 'JF2020081900008';

                this.initialize();
            }

            getOrderIdFromUrl() {
                // In a real app, you might get this from URL parameters
                const params = new URLSearchParams(window.location.search);
                return params.get('orderId');
            }

            async initialize() {

                // Fetch data from model
                const success = await this.model.fetchData(this.orderId);

                if (success) {
                    // Render all data
                    this.view.renderPatientInfo(this.model.patientData);
                    this.view.renderVisitInfo(this.model.visitData);
                    this.view.renderFeeDetails(this.model.feeItems);
                    this.view.renderOrderInfo(this.model.orderData);

                    // Bind event handlers
                    this.view.bindSaveNotes(this.handleSaveNotes.bind(this));
                    this.view.bindCancel(this.handleCancel.bind(this));
                } else {
                    this.view.showMessage('加载数据失败，请刷新重试', true);
                }
            }

            async handleSaveNotes(notes) {
                const success = await this.model.saveNotes(notes);

                if (success) {
                    this.view.showMessage('备注保存成功');
                } else {
                    this.view.showMessage('备注保存失败', true);
                }
            }

            handleCancel() {
                if (confirm('确定要取消吗？')) {
                    // 跳转到ShowDoorSpend页面
                    window.location.href = '/DoorSpend/ShowDoorSpend';
                }
            }
        }

        // Initialize the application when DOM is loaded
        document.addEventListener('DOMContentLoaded', () => {
            const model = new PatientBillingModel();
            const view = new PatientBillingView();
            new PatientBillingController(model, view);
        });
    </script>
</body>
</html>